# -*- coding: utf-8 -*-

from odoo import models, fields, api


class TdDynamicList(models.Model):
    _name = 'td.dynamic.list'
    _description = '动态显示列'

    model_name = fields.Char(string='模型名称', required=True)
    user_id = fields.Integer(string='用户', required=True)
    column_name = fields.Char(string='列id', required=True)
    invisible = fields.Boolean(string='是否显示', required=True)

    @api.model
    def save_dynamic_name(self, model_info):
        """
        {'model_name':model_name,'user_id':user_id, 'columns_info':[{'column_name':column_name,'invisible':True}]}
        """
        model_name = model_info.get('model_name', '')
        user_id = model_info.get('user_id', '')
        column_info = model_info.get('column_info', '')
        for col in column_info:
            column_name = col.get('column_name', '')
            if not column_name:
                continue
            invisible = col.get('invisible', '')
            domain = [('model_name', '=', model_name), ('user_id', '=', user_id), ('column_name', '=', column_name)]
            res = self.search(domain, limit=1)
            if res:
                if res.invisible != invisible:
                    res.write({
                        'invisible': invisible
                    })
            else:
                self.create({
                    'model_name': model_name,
                    'user_id': user_id,
                    'column_name': column_name,
                    'invisible': invisible
                })
        return {'res': 'ok'}

    @api.model
    def read_dynamic_name(self, model_name, user_id):
        domain = [('model_name', '=', model_name), ('user_id', '=', user_id)]
        results = self.search(domain)
        col_list = list()
        model_fields = list(dict(self.env[model_name]._fields).keys())
        for res in results:
            if res.column_name not in model_fields:
                res.unlink()
            else:
                attr = dict()
                attr['column_name'] = res.column_name
                attr['invisible'] = res.invisible
                col_list.append(attr)
        return col_list

    @api.model
    def read_all_field_name(self, model_name):
        fields_name = list(dict(self.env[model_name]._fields).keys())
        current_exist = self.search([('column_name', 'in', fields_name)])
        current_field = {res.column_name: res.invisible for res in current_exist}

        fields_list = list()
        for f_name in fields_name:
            fields_string = self.env[model_name]._fields[f_name].string
            attr = dict()
            attr['field_name'] = f_name
            attr['label'] = fields_string
            attr['invisible'] = current_field.get('f_name', True)
            fields_list.append(attr)

        print(fields_list)

        return fields_list
